package org.mclll.xwangplugin.web;


import com.google.common.collect.Maps;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.mclll.xwangplugin.log.GlobalLog;
import org.mclll.xwangplugin.log.LogUtil;
import org.mclll.xwangplugin.log.LoggerFactory;
import org.mclll.xwangplugin.web.controller.DefaultServlet;
import org.mclll.xwangplugin.web.util.HttpServlet;
import org.mclll.xwangplugin.web.util.MyServlet;
import org.reflections.Reflections;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

public class Application {
    public static LogUtil log = LoggerFactory.get(GlobalLog.class);
    public static Server server;
    public static Map<String, HttpServlet> servletMap;
    public static DefaultServlet defaultServlet = new DefaultServlet();
    public static void startHttpClient() {
        servletMap = Maps.newHashMap();
        Reflections reflections = new Reflections("org.mclll.xwangplugin.web.controller");
        for (Class<?> aClass : reflections.getTypesAnnotatedWith(MyServlet.class)) {
            MyServlet annotation = aClass.getAnnotation(MyServlet.class);
            try {
                String value = annotation.value();
                HttpServlet run = (HttpServlet) (aClass).getConstructor().newInstance();
                servletMap.put(value, run);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        server = new Server(25567);
        server.setHandler(new AbstractHandler() {
            @Override
            public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
                    throws IOException, ServletException {
                // 处理HTTP请求
                response.setContentType("text/html");
                response.setStatus(HttpServletResponse.SC_OK);
                HttpServlet orDefault = servletMap.getOrDefault(target, defaultServlet);
                response.getWriter().println(orDefault.run(baseRequest, request, response));
                baseRequest.setHandled(true);
            }
        });

        try {
            server.start(); // 启动HTTP服务器
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("Http服务启动成功");
    }

    public static void disableHttpClient() {
        try {
            if (server != null) {
                server.stop(); // 停止HTTP服务器
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
